package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.检查参数
        if(dto.getOperation() == null ||
                dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 判断是否有作者
        if(dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "作者信息不能为空");
        }
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if(apAuthor == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注用户不存在");
        }

        //3 判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 关注
        if (dto.getOperation() == 0) {

            //4 创建数据（app用户关注和app用户粉丝）
            return followByUserId(user.getId(),apAuthor.getUserId(),dto.getArticleId());
        } else { // 取消关注
            return followCancelByUserId(user.getId(),apAuthor.getUserId());
        }

    }


    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserFanMapper apUserFanMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 关注
     * @param userId   普通用户（当前登录人）
     * @param followUserId 被关注的作者对应的apUser id
     * @param articleId 文章id
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer followUserId, Long articleId) {
        //1.获取被关注的作者对应的apUser
        ApUser followUser = apUserMapper.selectById(followUserId);
        if(followUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注用户不存在");
        }
        if (userId.intValue() == followUser.getId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"无需关注自己");
        }

        //2 保存当前用户关注信息
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUser.getId())
                .eq(ApUserFollow::getUserId, userId));
        if (apUserFollow != null) {
             CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short)1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);

        //3 保存 被关注的作者对应的apUser 对应的粉丝（当前用户）
        //查询粉丝信息(站在当前文章作者角度考虑)
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId).eq(ApUserFan::getUserId, followUserId));
        if (apUserFan != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        apUserFan = new ApUserFan();
        apUserFan.setUserId(followUserId);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short)0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());
				 // 粉丝名称 
        ApUser apUser = apUserMapper.selectById(userId);
        apUserFan.setFansName(apUser.getName());

        apUserFanMapper.insert(apUserFan);

        //TODO 4 记录用户的行为
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setArticleId(articleId);
        dto.setFollowId(followUserId);
        dto.setUserId(apUser.getId());

        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));

        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 取消关注
     * @param userId   普通用户（当前登录人）
     * @param followUserId 被关注的作者对应的apUser id
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {

        // 删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));

        // 删除被关注的粉丝信息
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}